/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import { useEffect, useState } from 'react';
import clsx from 'clsx';
import Heading from '@theme/Heading';
import ShowcaseCard from '../ShowcaseCard';

import styles from './styles.module.css';


function HeadingNoResult() {
  return (
    <Heading as="h2">
      暂无数据
    </Heading>
  );
}

function NoResultSection() {
  return (
    <section className="margin-top--lg margin-bottom--xl">
      <div className="container padding-vert--md text--center">
        <HeadingNoResult />
      </div>
    </section>
  );
}

export default function ShowcaseCards() {
  const [communities, setCommunities] = useState([]);
  const [loading, setLoading] = useState(true);

  const getCommunities = () => {
    fetch("https://atomgit.com/api/pop_open/v1/page/communities", {
      "headers": {
        "content-type": "application/json",
      },
      "body": JSON.stringify({ "pageNum": 1, "pageSize": 999, "keywords": '' }),
      "method": "POST"
    })
      .then((res) => {
        if (!res.ok) {
          return;
        }
        return res.json();
      })
      .then((data) => {
        setCommunities(data?.records || []);
      })
      .catch((error) => {
        console.error('获取社区数据时出错:', error);
      })
      .finally(() => {
        setLoading(false);
      });
  }

  useEffect(() => {
    getCommunities();
  }, [])

  if (loading) {
    return (
      <section className="margin-top--lg margin-bottom--xl">
        <div className="container padding-vert--md text--center">
          加载中...
        </div>
      </section>
    );
  }

  if (communities?.length === 0) {
    return <NoResultSection />;
  }
  return (
    <section className="margin-top--lg margin-bottom--xl">
      <div className="container">
        <ul className={clsx('clean-list', styles.cardList)}>
          {communities?.length && (
            <>
              {communities.map((community) => (
                <ShowcaseCard item={community} key={community.communityId} />
              ))}
            </>
          )}
        </ul>
      </div>
    </section>
  );
}
